package com.crm.business.crm.controller;

import com.alibaba.fastjson.JSONObject;
import com.crm.business.crm.log.CrmRefundLog;
import com.crm.business.crm.service.ICrmReFundService;
import com.crm.business.crm.service.IHpPaymentTypeDictService;
import com.crm.common.crm.common.CrmModel;
import com.crm.common.crm.constant.CrmCodeEnum;
import com.crm.common.crm.constant.CrmEnum;
import com.crm.common.crm.constant.FieldEnum;
import com.crm.common.crm.entity.BO.CrmChangeOverdueBO;
import com.crm.common.crm.entity.BO.CrmChangeOwnerUserBO;
import com.crm.common.crm.entity.BO.CrmContractSaveBO;
import com.crm.common.crm.entity.BO.CrmUpdateInformationBO;
import com.crm.common.crm.entity.PO.CrmRefund;
import com.crm.common.crm.entity.PO.HpPaymentTypeDict;
import com.crm.common.crm.entity.VO.CrmInfoNumVO;
import com.crm.common.crm.entity.VO.CrmModelFiledVO;
import com.crm.common.ka.core.common.R;
import com.crm.common.ka.core.common.Result;
import com.crm.common.ka.core.common.SubModelType;
import com.crm.common.ka.core.common.log.BehaviorEnum;
import com.crm.common.ka.core.common.log.SysLog;
import com.crm.common.ka.core.common.log.SysLogHandler;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.common.ka.core.exception.CrmException;
import com.crm.common.crm.entity.BO.CrmSearchBO;
import com.crm.common.ka.core.servlet.upload.FileEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 退款表 前端控制器
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-05-28
 */
@RestController
@RequestMapping("/crmRefund")
@Api(tags = "退款模块接口")
@SysLog(subModel = SubModelType.CRM_REFUND,logClass = CrmRefundLog.class)
public class CrmRefundController {

    @Autowired
    private ICrmReFundService crmRefundService;

    @PostMapping("/queryPageList")
    @ApiOperation("查询列表页数据")
    public Result<BasePage<Map<String, Object>>> queryPageList(@RequestBody CrmSearchBO search) {
        search.setPageType(1);
        BasePage<Map<String, Object>> mapBasePage = crmRefundService.queryPageList(search);
        return R.ok(mapBasePage);
    }

    @PostMapping("/add")
    @ApiOperation("保存数据")
    @SysLogHandler(behavior = BehaviorEnum.SAVE,object = "#crmModel.entity.[number]",detail = "'新增了回款:' + #crmModel.entity.[number]")
    public Result add(@RequestBody CrmContractSaveBO crmModel) {

        //开户行省市县
        if (crmModel.getEntity().get("mapBankcardaddr") != null && crmModel.getEntity().get("mapBankcardaddr") != "") {
            String[] address = crmModel.getEntity().get("mapBankcardaddr").toString().split(",");
            if(address.length == 3){
                String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
                crmModel.getEntity().put("bankCardAddr", addr);
            }else if(address.length == 2){
                String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + "\"}";
                crmModel.getEntity().put("bankCardAddr", addr);
            }else if(address.length == 1){
                String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + "\", \"area\":\"" + "\"}";
                crmModel.getEntity().put("bankCardAddr", addr);
            }
        }

        crmRefundService.addOrUpdate(crmModel);
        return R.ok();
    }

    @PostMapping("/update")
    @ApiOperation("修改数据")
    @SysLogHandler(behavior = BehaviorEnum.UPDATE)
    public Result update(@RequestBody CrmContractSaveBO crmModel) {

        if (crmModel.getEntity().get("mapBankcardaddr") != null && crmModel.getEntity().get("mapBankcardaddr") != "") {

            if(crmModel.getEntity().get("mapBankcardaddr") instanceof String){
                String[] address = crmModel.getEntity().get("mapBankcardaddr").toString().split(",");
                if(address.length == 3){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
                    crmModel.getEntity().put("bankCardAddr", addr);
                }else if(address.length == 2){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + "\"}";
                    crmModel.getEntity().put("bankCardAddr", addr);
                }else if(address.length == 1){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + "\", \"area\":\"" + "\"}";
                    crmModel.getEntity().put("bankCardAddr", addr);
                }else{
                    crmModel.getEntity().put("bankCardAddr",address);
                }
            }else if (crmModel.getEntity().get("mapBankcardaddr") instanceof LinkedHashMap){
                String province = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapBankcardaddr")).get("province");
                String city = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapBankcardaddr")).get("city");
                String area = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapBankcardaddr")).get("area");
                String addr = "{\"province\":\"" + province + "\", \"city\":\"" + city + "\", \"area\":\"" + area + "\"}";
                crmModel.getEntity().put("bankCardAddr", addr);
            }
        }
        crmRefundService.addOrUpdate(crmModel);
        return R.ok();
    }

    @PostMapping("/checkOkEdit")
    @ApiOperation("修改数据")
    @SysLogHandler(behavior = BehaviorEnum.UPDATE)
    public Result checkOkEdit(@RequestBody CrmContractSaveBO crmModel){
        if (crmModel.getEntity().get("mapBankcardaddr") != null && crmModel.getEntity().get("mapBankcardaddr") != "") {

            if(crmModel.getEntity().get("mapBankcardaddr") instanceof String){
                String[] address = crmModel.getEntity().get("mapBankcardaddr").toString().split(",");
                if(address.length == 3){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
                    crmModel.getEntity().put("bankCardAddr", addr);
                }else if(address.length == 2){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + "\"}";
                    crmModel.getEntity().put("bankCardAddr", addr);
                }else if(address.length == 1){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + "\", \"area\":\"" + "\"}";
                    crmModel.getEntity().put("bankCardAddr", addr);
                }else{
                    crmModel.getEntity().put("bankCardAddr",address);
                }
            }else if (crmModel.getEntity().get("mapBankcardaddr") instanceof LinkedHashMap){
                String province = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapBankcardaddr")).get("province");
                String city = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapBankcardaddr")).get("city");
                String area = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapBankcardaddr")).get("area");
                String addr = "{\"province\":\"" + province + "\", \"city\":\"" + city + "\", \"area\":\"" + area + "\"}";
                crmModel.getEntity().put("bankCardAddr", addr);
            }
        }
        crmRefundService.checkOkEdit(crmModel);
        return R.ok();
    }

    @PostMapping("/queryById/{refundId}")
    @ApiOperation("根据ID查询")
    public Result<CrmModel> queryById(@PathVariable("refundId") @ApiParam(name = "id", value = "id") Integer refundId) {
        Integer number = crmRefundService.lambdaQuery().eq(CrmRefund::getRefundId,refundId).ne(CrmRefund::getCheckStatus,7).count();
        if (number == 0){
            throw new CrmException(CrmCodeEnum.CRM_DATA_DELETED,"退款");
        }
        CrmModel model = crmRefundService.queryById(refundId);
        return R.ok(model);
    }

    @PostMapping("/field")
    @ApiOperation("查询新增所需字段")
    public Result<List<CrmModelFiledVO>> queryField() {
        List<CrmModelFiledVO> crmModelFiledList = crmRefundService.queryField(null);
        return R.ok(crmModelFiledList);
    }

    @PostMapping("/field/{id}")
    @ApiOperation("查询修改数据所需信息")
    public Result<List<CrmModelFiledVO>> queryField(@PathVariable("id") @ApiParam(name = "id", value = "id") Integer id) {
        List<CrmModelFiledVO> crmModelFiledList = crmRefundService.queryField(id);
        return R.ok(crmModelFiledList);
    }

    @PostMapping("/checkOkEditField/{id}")
    @ApiOperation("查询修改数据所需信息")
    public Result<List<CrmModelFiledVO>> queryCheckOkEditField(@PathVariable("id") @ApiParam(name = "id", value = "id") Integer id) {
        List<CrmModelFiledVO> crmModelFiledList = crmRefundService.queryCheckOkEditField(id);
        return R.ok(crmModelFiledList);
    }

    @PostMapping("/deleteByIds")
    @ApiOperation("根据ID删除数据")
    @SysLogHandler(behavior = BehaviorEnum.DELETE)
    public Result deleteByIds(@ApiParam(name = "ids", value = "id列表") @RequestBody List<Integer> ids) {
        crmRefundService.deleteByIds(ids);
        return R.ok();
    }

    @PostMapping("/changeOwnerUser")
    @ApiOperation("修改退款负责人")
    @SysLogHandler(behavior = BehaviorEnum.CHANGE_OWNER)
    public Result changeOwnerUser(@RequestBody CrmChangeOwnerUserBO crmChangeOwnerUserBO){
        crmRefundService.changeOwnerUser(crmChangeOwnerUserBO.getIds(),crmChangeOwnerUserBO.getOwnerUserId());
        return R.ok();
    }

    @PostMapping("/changeRefundUser")
    @ApiOperation("修改退款负责人")
    @SysLogHandler(behavior = BehaviorEnum.CHANGE_OWNER)
    public Result changeRefundUser(@RequestBody CrmChangeOwnerUserBO crmChangeOwnerUserBO){
        crmRefundService.changeRefundUser(crmChangeOwnerUserBO.getIds(),crmChangeOwnerUserBO.getRefundUserId());
        return R.ok();
    }

    @PostMapping("/changeTeacherUser")
    @ApiOperation("修改退款讲师负责人")
    public Result changeTeacherUser(@RequestBody CrmChangeOwnerUserBO crmChangeOwnerUserBO){
        crmRefundService.changeTeacherUser(crmChangeOwnerUserBO);
        return R.ok();
    }

    @PostMapping("/information/{id}")
    @ApiOperation("查询详情页信息")
    public Result<List<CrmModelFiledVO>> information(@PathVariable("id") @ApiParam(name = "id", value = "id") Integer id) {
        List<CrmModelFiledVO> information = crmRefundService.information(id);
        return R.ok(information);
    }

    @PostMapping("/queryFileList")
    @ApiOperation("查询附件列表")
    public Result<List<FileEntity>> queryFileList(@RequestParam("id") @ApiParam(name = "id", value = "id") Integer id) {
        List<FileEntity> fileEntities = crmRefundService.queryFileList(id);
        return R.ok(fileEntities);
    }

    @PostMapping("/num")
    @ApiOperation("详情页数量展示")
    public Result<CrmInfoNumVO> num(@RequestParam("id") @ApiParam(name = "id", value = "id") Integer id) {
        CrmInfoNumVO infoNumVO = crmRefundService.num(id);
        return R.ok(infoNumVO);
    }

    @PostMapping("/batchExportExcel")
    @ApiOperation("选中导出")
    @SysLogHandler(behavior = BehaviorEnum.EXCEL_EXPORT,object = "退款导出",detail = "选中导出")
    public void batchExportExcel(@RequestBody @ApiParam(name = "ids", value = "id列表") List<Integer> ids, HttpServletResponse response) {
        CrmSearchBO search = new CrmSearchBO();
        search.setPageType(10000);
        search.setLabel(CrmEnum.RECEIVABLES.getType());
        CrmSearchBO.Search entity = new CrmSearchBO.Search();
        entity.setFormType(FieldEnum.TEXT.getFormType());
        entity.setSearchEnum(CrmSearchBO.FieldSearchEnum.ID);
        entity.setValues(ids.stream().map(Object::toString).collect(Collectors.toList()));
        search.getSearchList().add(entity);
        search.setPageType(10000);
        crmRefundService.exportExcel(response, search);
    }

    @PostMapping("/allExportExcel")
    @ApiOperation("全部导出")
    @SysLogHandler(behavior = BehaviorEnum.EXCEL_EXPORT,object = "退款导出",detail = "全部导出")
    public void allExportExcel(@RequestBody CrmSearchBO search, HttpServletResponse response) {
        search.setPageType(10000);
        crmRefundService.exportExcel(response, search);
    }

    @PostMapping("/updateInformation")
    @ApiOperation("基本信息保存修改")
    @SysLogHandler(behavior = BehaviorEnum.UPDATE)
    public Result updateInformation(@RequestBody CrmUpdateInformationBO updateInformationBO) {
        crmRefundService.updateInformation(updateInformationBO);
        return R.ok();
    }

    @Autowired
    private IHpPaymentTypeDictService paymentTypeDictService;

    @PostMapping("/queryPaymentTypeDicList")
    @ApiOperation("查询列表页数据")
    public Result<String> queryPaymentTypeDicList() {
        List<HpPaymentTypeDict> mapBasePage = paymentTypeDictService.queryPaymentTypeDicListByParentId(0);
        return R.ok(JSONObject.toJSONString(mapBasePage));
    }

    @PostMapping("/changeOverdue")
    @ApiOperation("修改逾期状态")
    public Result changeOverdue(@RequestBody CrmChangeOverdueBO changeOverdueBO){
//        this.crmRefundService.changeOverdue(changeOverdueBO.getIds(), changeOverdueBO.getOverdueStatus());
        return Result.ok();
    }

    @PostMapping("/queryOverdueStatus")
    @ApiOperation("获取逾期状态信息")
    public Result queryOverdueStatus(){
//        List<String> options = this.crmRefundService.queryOverdueStatus();
        return Result.ok();
    }

}

